const http = require('http');
const url = require('url');
const querystring = require('querystring');

const LISTEN_PORT = parseInt(process.argv[2]) || 8088;

http.createServer((req, res) => {
        let reqUrl = url.parse(req.url, true);
        let returnData;

        if (/^\/api\/parsetime/.test(reqUrl.pathname)) {
            returnData = timeStrParse(reqUrl.query.iso);
        } else if (/^\/api\/unixtime/.test(reqUrl.pathname)) {
            returnData = strToTime(reqUrl.query.iso);
        }
        if (returnData) {
            res.end(JSON.stringify(returnData));
        } else {
            res.writeHead(404);
            res.end('not found');
        }
    }).on('error', console.error)
    .listen(LISTEN_PORT);

function strToTime(timeStr) {
    return {
        unixtime: (new Date(timeStr) || new Date()).getTime()
    };
}

function timeStrParse(timeStr) {
    let date = new Date(timeStr) || new Date();
    return {
        hour: date.getHours(),
        minute: date.getMinutes(),
        second: date.getSeconds()
    };
}